package com.qf.fmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.fmall.dao.OrderItemMapper;
import com.qf.fmall.dao.OrdersMapper;
import com.qf.fmall.dao.ProductSkuMapper;
import com.qf.fmall.dao.ShoppingCartMapper;
import com.qf.fmall.entity.*;
import com.qf.fmall.service.OrderService;
import com.qf.fmall.service.ShoppingCartService;
import com.qf.fmall.utils.WxpayUtils;
import com.qf.fmall.vo.PageInfoVo;
import com.qf.fmall.vo.ResStatus;
import com.qf.fmall.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author 王权富贵
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private ShoppingCartService shoppingCartService;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private OrdersMapper ordersMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private OrderItemMapper orderItemMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private ProductSkuMapper productSkuMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo addOrders(String cids, Orders orders) {
        /*
            1, 判断商品是否充足
            2，添加主表
            3，添加快照表
            4，修改商品库存数量
            5，删除购物车

        */
        ResultVo resultVo = shoppingCartService.listByCids(cids);
        List<ShoppingCartVo> list = (List<ShoppingCartVo>) resultVo.getData();
        Boolean flag = true;
        StringBuilder stringBuilder = new StringBuilder();
        for (ShoppingCartVo shoppingCartVo : list) {
            stringBuilder.append(shoppingCartVo.getProductName()).append(",");
            if (shoppingCartVo.getStock() < Integer.parseInt(shoppingCartVo.getCartNum())) {
                flag = false;
            }
        }
        ResultVo vo = new ResultVo();
        if (flag) {
            String orderId = UUID.randomUUID().toString().replaceAll("-", "");
            orders.setOrderId(orderId);
            orders.setUntitled(stringBuilder.toString());
            orders.setCreateTime(new Date());
            orders.setStatus("1");
            ordersMapper.insert(orders);
            System.out.println(orderId);
            for (ShoppingCartVo lvo : list) {
                System.out.println(lvo);
                OrderItem orderItem = new OrderItem(
                        UUID.randomUUID().toString().replaceAll("-", ""),
                        orderId,
                        lvo.getProductId(),
                        lvo.getProductName(),
                        lvo.getProductImg(),
                        lvo.getSkuId(),
                        lvo.getSkuName(),
                        lvo.getProductPrice(),
                        Integer.valueOf(lvo.getCartNum()),
                        new BigDecimal(lvo.getSellPrice() * Integer.valueOf(lvo.getCartNum())),
                        new Date(),
                        new Date(),
                        0
                );
                orderItemMapper.insert(orderItem);
            }
            for (ShoppingCartVo sku : list) {
                int stack = sku.getStock() - Integer.parseInt(sku.getCartNum());
                ProductSku productSku = new ProductSku();
                productSku.setStatus(stack);
                productSku.setSkuId(sku.getSkuId());
                productSkuMapper.updateByPrimaryKeySelective(productSku);
            }
            String[] split = cids.split(",");
            for (String cid : split) {
                shoppingCartMapper.deleteByPrimaryKey(cid);
            }
            //调用微信接口
            String payUrl = "";
            try {
                payUrl = WxpayUtils.getPayUrl(orderId);
                System.out.println("wx url: " + payUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("payUrl", payUrl);
            vo.setCode(ResStatus.OK);
            vo.setMsg("success");
            vo.setData(map);
        } else {
            vo.setCode(ResStatus.NO);
            vo.setMsg("购买失败");
        }
        return vo;
    }

    @Override
    public ResultVo statusOrders(String oid) {
        ResultVo resultVo = new ResultVo();
        Orders orders = new Orders();
        try {
            String queryOrder = WxpayUtils.queryOrder(oid);
            if ("SUCCESS".equals(queryOrder)) {
                resultVo.setCode(ResStatus.OK);
                resultVo.setMsg("success");
                resultVo.setData("2");
                orders.setOrderId(oid);
                orders.setStatus("2");
                orders.setPayType(1);
                orders.setPayTime(new Date());
                ordersMapper.updateByPrimaryKeySelective(orders);
            } else {
                resultVo.setCode(ResStatus.NO);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultVo;
    }

    @Override
    public ResultVo ListOrders(Integer userId, Integer pageNum, Integer limit) {
        Example example = new Example(Orders.class);
        example.createCriteria().andEqualTo("userId", userId);
        example.orderBy("createTime").desc();
        PageHelper.startPage(pageNum, limit);
        List<Orders> orders = ordersMapper.selectByExample(example);
        PageInfo<Orders> pageInfo = new PageInfo<>(orders);
        PageInfoVo<Orders> pageInfoVo = new PageInfoVo<>();
        pageInfoVo.setCount((int) pageInfo.getTotal());
        pageInfoVo.setList(pageInfo.getList());
        ResultVo resultVo = new ResultVo();
        if (orders.size() == 0) {
            resultVo.setCode(ResStatus.NO);
        } else {
            resultVo.setCode(ResStatus.OK);
            resultVo.setMsg("success");
            resultVo.setData(pageInfoVo);
        }
        return resultVo;
    }


}
